package com.bpzj.web.spring.file;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Created by bpzj on 2019-5-22.
 */
@Slf4j
@RestController
public class UploadFileController {

  private static final String UPLOAD_PATH = "D:\\";

  @PostMapping(value = "/upload")
  public String upload(@RequestParam("type") String type, @RequestPart("file") MultipartFile file) {

    // 保存文件
    String savedName = file.getOriginalFilename();
    Path savedPath = Paths.get(UPLOAD_PATH, savedName);
    File dest = savedPath.toFile();
    // 判断文件路径是否存在
    if (!dest.getParentFile().exists()) {
      dest.getParentFile().mkdirs();
    }
    // 文件写入
    try {
      file.transferTo(dest);
      log.info("文件保存到本地成功");
    } catch (IOException e) {
      log.info("文件保存到本地失败" + e);
      //  other code
    }
    return "文件保存完成";
  }

}
